# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re

from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection
from users.models import User


class RegisterView(View):

    def post(self, request):
        '''实现注册接口'''

        # 1.接收json参数，获取每一个
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')
        phone_code_client = dict.get('phonecode')

        # 2.整体检验，查看是否空值
        if not all([mobile, password, phone_code_client]):
            return JsonResponse({'errno': 4002,
                                 'errmsg': '缺少必传参数'})

        # 3.查询mobile在MySQL中的个数，判断是否注册
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '数据库查询错误'})

        # 4.如果存在返回结果(json)
        if count:
            return JsonResponse({'err': 4003,
                                 'errmsg': '该手机号已注册'})

        # 5.mobile是否为手机号格式
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 4004,
                                 'errmsg': 'mobile不满足格式要求'})
        # 6.password是否为8-20位
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 4004,
                                 'errmsg': 'password不满足格式要求'})
        # 7.验证码是否为6位数字
        if not re.match(r'^[0-9]{6}$', phone_code_client):
            return JsonResponse({'errno': 4004,
                                 'errmsg': 'phonecode不满足格式要求'})

        # 8.链接redis，获取redis的链接对象
        redis_conn = get_redis_connection('verify_code')

        # 9.从redis中获取保存的短信验证码
        phone_code_server = redis_conn.get('sms_%s' % mobile)
        if not phone_code_server:
            return JsonResponse({'errno': 4002,
                                 'errmsg': '短信验证码过期'})

        # 10.把前后端的短信验证码进行比对
        if phone_code_client != phone_code_server.decode():
            return JsonResponse({'errno': 4004,
                                 'errmsg': '输入的短信验证码不对'})

        # 11.把前段传入的mobile，password保存到User,username先存手机号
        try:
            user = User.objects.create_user(username=mobile,
                                            mobile=mobile,
                                            password=password)
        except Exception as e:
            return JsonResponse({'errno': 4302,
                                 'errmsg': '数据库保存失败'})

        # 补充：实现状态保持：
        login(request, user)

        # # 12.返回结果(json)

        response = JsonResponse({'errno': 0,
                                 'errmsg': '注册成功'})
        response.set_cookie('name', user.username, max_age=3600 * 24 * 14)
        return response


class LoginView(View):

    def post(self, request):
        '''实现登录接口'''

        # 1. 接收参数
        dict = json.loads(request.body.decode())
        username = dict.get('mobile')
        password = dict.get('password')

        # 2. 校验（整体 + 单个）
        if not all([username, password]):
            return JsonResponse({'errno': 400,
                                 'errmsg': '缺少必传参数'})

        # 3.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 4004,
                                 'errmsg': 'password格式有误'})

        # 4.验证是否能够登陆
        user = authenticate(username=username,
                            password=password)

        # 5.判断user是否为空，如果为空则返回
        if user is None:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '用户名或者密码错误'})

        # 6. 状态保持
        login(request, user)
        request.session.set_expiry(None)

        # 9.返回json
        return JsonResponse({'errno': 0,
                             'errmsg': '登陆成功'})

    def get(self, request):
        '''判断是否登录'''

        if request.user.is_authenticated:
            user = request.user
            user_id = request.session.get("_auth_user_id")
            response = JsonResponse({'errno': 0,
                                     'errmsg': '已登录',
                                     'data': {"name": user.username,
                                              "user_id": user_id}})
            return response
        else:
            return JsonResponse({"errno": "4101",
                                 "errmsg": "未登录"})

    def delete(self, request):
        '''退出登录(删除session&cookie)'''

        # 清理 session
        logout(request)

        # 创建 response 对象.
        response = JsonResponse({'errno': 0,
                                 'errmsg': '已登出'})

        # 调用对象的 delete_cookie 方法, 清除cookie
        response.delete_cookie('name')

        # 返回响应
        return response
